package com.cy.pj.ajax.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/")
public class AjaxController {

    private List<Map<String,Object>> list=new ArrayList<>();
    public AjaxController(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", "1");
        map.put("name", "华为");
        map.put("remark", "好");
        list.add(map);
    }

    //update
    @RequestMapping("doAjaxUpdate")
    public String doAjaxUpdate(@RequestParam Map<String,Object> map){
        Iterator<Map<String, Object>> it = list.iterator();
        while (it.hasNext()){
            Map<String, Object> map1 = it.next();
            if (map1.get("id").equals(map.get("id"))){
                map1.put("name", map.get("name"));
                map1.put("remark", map.get("remark"));
            }
        }
        return "update ok";
    }

    //delete请求
    @RequestMapping("doAjaxDelete/{id}")
    public String doAjaxDelete(@PathVariable Integer id){
        Iterator<Map<String, Object>> it = list.iterator();
        while (it.hasNext()){
            Map<String, Object> map = it.next();
            if (map.get("id").equals(String.valueOf(id))){
                System.out.println(map.get(id));
                it.remove();
            }
        }
        return "delete ok";
    }

    //post请求
    @RequestMapping("doAjaxPost")
    public String doAjaxPost(@RequestParam Map<String,Object> map){
        list.add(map);
        return "save ok";
    }

    //get请求
    @RequestMapping("doAjaxGet")
    public List<Map<String,Object>> doAjaxGet(){
        return list;
    }

    @RequestMapping("doAjaxStart")
    public String doAjaxStart() throws InterruptedException {
        Thread.sleep(5000);
        return "Response Result Of Ajax Get Request 01";
    }
}
